package com.fa.ojcodesandbox.controller;

import com.fa.ojcodesandbox.JavaDockerCodeSandbox;
import com.fa.ojcodesandbox.JavaNativeCodeSandbox;
import com.fa.ojcodesandbox.model.ExecuteCodeRequest;
import com.fa.ojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: MainController
 * Package: com.fa.ojcodesandbox.controller
 * Description:
 *
 * @Author:
 * @Create: 2024/4/27 - 9:38
 * @Version: v1.0
 */
@RestController
@RequestMapping("/main")
@CrossOrigin
public class MainController {

    // 为了保证安全性，定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    @Resource
    private JavaDockerCodeSandbox javaDockerCodeSandbox;


    /**
     * 执行代码docker代码沙箱，这个接口需要开启docker容器
     */
    @PostMapping("/executeCode/docker")
    ExecuteCodeResponse executeUserCodeDockerSandbox(@RequestBody ExecuteCodeRequest executeCodeRequest,
                                        HttpServletRequest request, HttpServletResponse response) {
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        // 进行简单的鉴权认证，请求该路径时，必须带上请求头
        if (!authHeader.equals(AUTH_REQUEST_SECRET)) {
            // 禁止访问
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new IllegalArgumentException("请求参数为空");
        }
        return javaDockerCodeSandbox.executeCode(executeCodeRequest);
    }

    /**
     * 执行代码
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeUserCode(@RequestBody ExecuteCodeRequest executeCodeRequest,
                                        HttpServletRequest request, HttpServletResponse response) {
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        // 进行简单的鉴权认证，请求该路径时，必须带上请求头
        if (!authHeader.equals(AUTH_REQUEST_SECRET)) {
            // 禁止访问
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new IllegalArgumentException("请求参数为空");
        }
        return javaNativeCodeSandbox.executeCode(executeCodeRequest);
    }

}
